Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨ Feat: Offer more forking options and test docs #1510

Merged

Conversation

roninjin10
Copy link
Collaborator

@roninjin10 roninjin10 commented Feb 24, 2025

Description

Concise description of proposed changes

Testing

Explain the quality checks that have been done on the code changes

Additional Information

Your ENS/address:

Summary by CodeRabbit

  • New Features
    • Introduced the ability to pass viem style transports to the Tevm framework, enhancing integration across multiple packages.
  • Documentation
    • Updated documentation to reflect new transport capabilities and improved error handling in transaction management.
  • Chores
    • Added new dependencies to support the updated transport functionality and improved state management features.

Copy link

vercel bot commented Feb 24, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Updated (UTC)
node ✅ Ready (Inspect) Visit Preview Feb 24, 2025 4:08am
1 Skipped Deployment
Name Status Preview Updated (UTC)
tevm-monorepo-tevm ⬜️ Ignored (Inspect) Feb 24, 2025 4:08am

Copy link

changeset-bot bot commented Feb 24, 2025

🦋 Changeset detected

Latest commit: 22d5afe

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 59 packages
Name Type
@tevm/state Patch
@tevm/node Patch
@tevm/base-bundler Patch
@tevm/bun-plugin Patch
@tevm/bundler-cache Patch
@tevm/compiler Patch
@tevm/config Patch
@tevm/esbuild-plugin Patch
@tevm/resolutions Patch
@tevm/rollup-plugin Patch
@tevm/rspack-plugin Patch
@tevm/runtime Patch
@tevm/solc Patch
tevm-run Patch
@tevm/unplugin Patch
@tevm/vite-plugin Patch
@tevm/webpack-plugin Patch
@tevm/whatsabi Patch
@tevm/cli Patch
@tevm/tsconfig Patch
@tevm/tsupconfig Patch
@tevm/revm Patch
@tevm/schemas Patch
@tevm/experimental-solc Patch
@tevm/viem-effect Patch
@tevm/ethers Patch
@tevm/viem Patch
@tevm/lsp Patch
@tevm/ts-plugin Patch
@tevm/vscode Patch
@tevm/actions Patch
@tevm/address Patch
@tevm/block Patch
@tevm/blockchain Patch
@tevm/client-types Patch
@tevm/common Patch
@tevm/contract Patch
@tevm/decorators Patch
@tevm/effect Patch
@tevm/errors Patch
@tevm/evm Patch
@tevm/http-client Patch
@tevm/jsonrpc Patch
@tevm/logger Patch
@tevm/memory-client Patch
@tevm/precompiles Patch
@tevm/predeploys Patch
@tevm/procedures Patch
@tevm/receipt-manager Patch
@tevm/rlp Patch
@tevm/server Patch
@tevm/sync-storage-persister Patch
@tevm/trie Patch
@tevm/tx Patch
@tevm/txpool Patch
@tevm/utils Patch
@tevm/vm Patch
@tevm/test-utils Patch
tevm Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@roninjin10 roninjin10 marked this pull request as ready for review February 24, 2025 00:09
Copy link
Contributor

coderabbitai bot commented Feb 24, 2025

Important

Review skipped

Review was skipped as selected files did not have any reviewable changes.

💤 Files selected but had no reviewable changes (36)
  • docs/node/docs/pages/advanced/txpool.mdx
  • docs/node/docs/pages/api/evm.mdx
  • docs/node/docs/pages/examples/ethers.mdx
  • docs/node/docs/pages/examples/forking-mainnet.test.ts
  • docs/node/docs/pages/examples/local-testing.test.ts
  • docs/node/docs/pages/examples/viem.mdx
  • docs/node/package.json
  • docs/node/tests/advanced/custom-precompiles.test.ts
  • docs/node/tests/advanced/receipts-and-logs.test.ts
  • docs/node/tests/advanced/txpool.test.ts
  • docs/node/tests/api/account-management.test.ts
  • docs/node/tests/api/actions.test.ts
  • docs/node/tests/api/block.test.ts
  • docs/node/tests/api/common.test.ts.todo
  • docs/node/tests/api/evm-events.test.ts.todo
  • docs/node/tests/api/evm.test.ts
  • docs/node/tests/api/memory-client.test.ts
  • docs/node/tests/api/methods.test.ts
  • docs/node/tests/api/receipt-manager.test.ts.todo
  • docs/node/tests/api/state.test.ts
  • docs/node/tests/api/tevm-call.test.ts
  • docs/node/tests/api/tx.test.ts.todo
  • docs/node/tests/api/utils.test.ts
  • docs/node/tests/core/create-tevm-node.test.ts
  • docs/node/tests/core/forking.test.ts.todo
  • docs/node/tests/core/managing-state.test.ts
  • docs/node/tests/core/tevm-node-interface.test.ts.todo
  • docs/node/tests/examples/debugger-ui.test.ts.todo
  • docs/node/tests/examples/ethers.test.ts
  • docs/node/tests/examples/forking-mainnet.test.ts
  • docs/node/tests/examples/local-testing.test.ts.todo
  • docs/node/tests/examples/viem.test.ts
  • docs/node/tests/getting-started.test.ts
  • docs/node/tests/introduction/architecture-overview.test.ts
  • packages/node/src/createTevmNode.js
  • packages/state/src/actions/getForkClient.js
⛔ Files ignored due to path filters (92)
  • docs/node/docs/dist/.vocs/icons/arrow-diagonal.svg is excluded by !**/dist/**, !**/*.svg
  • docs/node/docs/dist/.vocs/icons/chevron-down.svg is excluded by !**/dist/**, !**/*.svg
  • docs/node/docs/dist/.vocs/icons/chevron-up.svg is excluded by !**/dist/**, !**/*.svg
  • docs/node/docs/dist/.vocs/icons/link.svg is excluded by !**/dist/**, !**/*.svg
  • docs/node/docs/dist/.vocs/search-index-6b680a3c.json is excluded by !**/dist/**
  • docs/node/docs/dist/advanced/custom-precompiles/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/advanced/performance-profiler/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/advanced/receipts-and-logs/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/advanced/txpool/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/api/account-management/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/api/actions/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/api/block/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/api/blockchain/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/api/common/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/api/contracts/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/api/decorators/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/api/evm-events/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/api/evm/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/api/json-rpc/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/api/memory-client/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/api/methods/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/api/receipt-manager/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/api/state/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/api/tevm-call/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/api/tx/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/api/txpool/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/api/utils/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/api/vm-and-submodules/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/api/vm/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/assets/account-management-C6sME-FF.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/actions-ysgIFOhr.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/architecture-overview-D0mXZo6-.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/block-BOBd-XXn.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/blockchain-zInxtXoP.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/common-DxbgwiEY.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/contracts-FFHUZRTR.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/create-tevm-node-BSI3dNSV.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/custom-precompiles-NK7JiO9B.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/debugger-ui--SgcNgX7.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/decorators-B5KjQtzb.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/ethers-EPB6SqtR.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/evm-BtJObDOA.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/evm-events-BljMxaNg.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/forking-BffJZuBY.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/forking-mainnet-Eimovd1l.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/getting-started-CWiAntJK.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/index-B3fhLnWZ.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/index-Clh8v8D-.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/installation-BpAt-zgL.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/json-rpc-BO9KkMto.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/local-testing-4gbJSZ33.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/managing-state-Xq2AamQk.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/memory-client-DgeUNJBQ.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/methods-CgZDaShF.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/performance-profiler-CfeKcunA.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/receipt-manager-bHS00M1g.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/receipts-and-logs-C5Dk-in6.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/state-Ct18hl7I.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/style-aVuz2OLc.css is excluded by !**/dist/**
  • docs/node/docs/dist/assets/tevm-call-BgMlFoE2.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/tevm-node-interface-Cv4LW7R3.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/tx-B1zSQgQY.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/txpool-BuKa6ks5.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/txpool-D8RQC-q4.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/utils-D2dtB2TM.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/viem-DmrLA7b5.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/vm-and-submodules-D_pEVVDr.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/vm-iziBhQyD.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/what-is-tevm-node-CywzrMwq.js is excluded by !**/dist/**
  • docs/node/docs/dist/assets/why-run-ethereum-in-js-C70BoTrt.js is excluded by !**/dist/**
  • docs/node/docs/dist/core/create-tevm-node/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/core/forking/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/core/managing-state/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/core/tevm-node-interface/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/examples/debugger-ui/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/examples/ethers/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/examples/forking-mainnet/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/examples/local-testing/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/examples/viem/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/getting-started/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/initializeTheme.iife.js is excluded by !**/dist/**
  • docs/node/docs/dist/introduction/architecture-overview/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/introduction/installation/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/introduction/what-is-tevm-node/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/introduction/why-run-ethereum-in-js/index.html is excluded by !**/dist/**
  • docs/node/docs/dist/llms-full.txt is excluded by !**/dist/**
  • docs/node/docs/dist/llms.txt is excluded by !**/dist/**
  • packages/node/src/__snapshots__/createTevmNode.spec.ts.snap is excluded by !**/*.snap
  • packages/node/src/__snapshots__/getBlockNumber.spec.ts.snap is excluded by !**/*.snap
  • packages/node/src/__snapshots__/statePersister.spec.ts.snap is excluded by !**/*.snap
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This pull request introduces a new feature to support viem style transports across the Tevm framework. Multiple packages have been updated to handle transports flexibly by conditionally extracting the request property when the transport is a function. Key functions in node packages and state actions have been modified, and the interface for fork options now accepts a union type. Additionally, documentation and the dependency specification have been revised to reflect these changes.

Changes

File(s) Change Summary
.changeset/smart-buses-brake.md Introduces the feature to allow viem style transports across Tevm and updates documentation.
docs/node/package.json Adds new dependencies: "tevm": "workspace:^" and "viem": "^2.23.5".
packages/node/src/createTevmNode.js, packages/state/src/actions/getForkClient.js Updates fork transport handling to conditionally extract the request property from either a function call (fork.transport({})) or directly from an object.
packages/node/src/getBlockNumber.js, packages/node/src/getChainId.js Modifies the client parameter type to a union type and adds a conditional check to derive the transport properly.
packages/state/src/state-types/ForkOptions.ts Updates the ForkOptions interface by importing Transport from viem and changing the transport property to a union type.
docs/node/docs/pages/advanced/custom-precompiles.mdx, docs/node/docs/pages/advanced/custom-precompiles.test.ts Enhances error handling and gas limit checks in precompile functions, updating method signatures and test cases accordingly.
docs/node/docs/pages/advanced/receipts-and-logs.mdx, docs/node/docs/pages/advanced/receipts-and-logs.test.ts Introduces new functionality for transaction handling and error management within the ReceiptsManager module and updates tests for improved functionality.
docs/node/docs/pages/core/create-tevm-node.mdx, docs/node/docs/pages/core/create-tevm-node.test.ts Updates the documentation and tests for creating a Tevm Node, including changes to transport handling and contract definitions.
docs/node/docs/pages/core/managing-state.mdx, docs/node/docs/pages/core/managing-state.test.ts Refactors address handling and introduces utility functions for managing Ethereum accounts and storage.

Sequence Diagram(s)

sequenceDiagram
    participant C as Caller
    participant F as Function
    participant T as Transport Provider

    C->>F: Call with options/fork with transport
    alt Transport is a function
        F->>T: Call transport({})
        T-->>F: Return { request }
    else Transport is an object
        F-->>F: Access transport.request directly
    end
    F-->>C: Return configured Tevm Node / execute fetcher with proper transport
Loading

Possibly related PRs

  • 👷 Address-prod #1447: The changes in the main PR involve the introduction of the createAddress function and its usage across various modules, which is directly related to the modifications in this PR that also focus on the createAddress function.
  • ✅ Test: Add TxPool tests #1326: The changes enhance the handling of transport properties and introduce new utility functions for transaction management, related to the PR that adds tests for the TxPool component.
  • ✅ Test: Add a bunch of viem api tests #1109: The changes enhance the Tevm framework to support viem style transports, which are directly related to modifications in the PR that adds tests for the viem API.

Poem

In the code fields, I hop and play,
Transport paths now lead the way.
If it's a function, I call with glee,
Else, I pick the request naturally.
With viem magic in every byte,
This rabbit celebrates a feature so bright! 🐇


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Collaborator Author

This stack of pull requests is managed by Graphite. Learn more about stacking.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (5)
packages/state/src/state-types/ForkOptions.ts (1)

2-2: LGTM! Consider adding JSDoc comments.

The changes correctly expand transport support to include both EIP1193 and viem style transports. Consider adding JSDoc comments to document the supported transport types and provide usage examples.

 import { type EIP1193RequestFn, type Transport } from 'viem'

 export interface ForkOptions {
+  /**
+   * Transport configuration for forking
+   * @example
+   * // Using EIP1193 transport
+   * transport: { request: myEIP1193RequestFn }
+   * // Using viem transport
+   * transport: myViemTransport
+   */
 	transport: { request: EIP1193RequestFn } | Transport
 	blockTag?: BlockTag | bigint
 }

Also applies to: 5-5

packages/node/src/getChainId.js (1)

5-5: LGTM! Consider enhancing error handling.

The changes correctly handle both transport types. Consider adding error handling for invalid transport types and documenting the expected transport format.

 /**
  * @param {{request: import('viem').EIP1193RequestFn} | import('viem').Transport} client
+ * @throws {Error} When transport is invalid or missing request method
  */
 export const getChainId = async (client) => {
+	if (!client) {
+		throw new Error('Client is required')
+	}
 	const transport = typeof client === 'function' ? client({}) : client
+	if (!transport.request || typeof transport.request !== 'function') {
+		throw new Error('Invalid transport: missing request method')
+	}
 	const fetcher = createJsonRpcFetcher(transport)

Also applies to: 8-9

packages/node/src/getBlockNumber.js (1)

5-5: Consider extracting common transport handling logic.

The transport handling logic is duplicated across getBlockNumber.js and getChainId.js. Consider extracting this into a shared utility function.

Create a new utility file packages/node/src/utils/createTransportFetcher.js:

/**
 * Creates a JSON-RPC fetcher from a transport
 * @param {{request: import('viem').EIP1193RequestFn} | import('viem').Transport} client
 * @throws {Error} When transport is invalid or missing request method
 */
export const createTransportFetcher = (client) => {
  if (!client) {
    throw new Error('Client is required')
  }
  const transport = typeof client === 'function' ? client({}) : client
  if (!transport.request || typeof transport.request !== 'function') {
    throw new Error('Invalid transport: missing request method')
  }
  return createJsonRpcFetcher(transport)
}

Then update both files to use this utility:

-	const transport = typeof client === 'function' ? client({}) : client
-	const fetcher = createJsonRpcFetcher(transport)
+	const fetcher = createTransportFetcher(client)

Also applies to: 8-9

packages/state/src/actions/getForkClient.js (1)

31-33: Consider enhancing error handling for transport request extraction.

The transport request extraction could benefit from additional error handling to ensure the request property exists.

-				request: typeof fork.transport === 'function'
-					? fork.transport({}).request
-					: fork.transport.request,
+				request: (() => {
+					const transport = typeof fork.transport === 'function'
+						? fork.transport({})
+						: fork.transport
+					if (!transport?.request || typeof transport.request !== 'function') {
+						throw new Error('Invalid fork transport: missing request method')
+					}
+					return transport.request
+				})(),
packages/node/src/createTevmNode.js (1)

389-395: Consider adding runtime type validation.

While the implementation is correct, consider adding runtime validation to ensure the transport function returns an object with a request method.

 ...(options.fork?.transport ? {
   forkTransport: {
     request: typeof options.fork.transport === 'function'
-      ? /** @type {import('viem').Transport} */ (options.fork.transport)({}).request
+      ? (() => {
+          const transport = options.fork.transport({});
+          if (!transport || typeof transport.request !== 'function') {
+            throw new Error('Transport function must return an object with a request method');
+          }
+          return transport.request;
+        })()
       : options.fork.transport.request
   }
 } : {}),
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 27b4a06 and 970842e.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (7)
  • .changeset/smart-buses-brake.md (1 hunks)
  • docs/node/package.json (1 hunks)
  • packages/node/src/createTevmNode.js (3 hunks)
  • packages/node/src/getBlockNumber.js (1 hunks)
  • packages/node/src/getChainId.js (1 hunks)
  • packages/state/src/actions/getForkClient.js (1 hunks)
  • packages/state/src/state-types/ForkOptions.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: Nx Cloud Agents (6)
  • GitHub Check: Nx Cloud Agents (5)
  • GitHub Check: Nx Cloud Agents (4)
  • GitHub Check: Nx Cloud Agents (3)
  • GitHub Check: Nx Cloud Agents (2)
  • GitHub Check: Nx Cloud Agents (1)
  • GitHub Check: Nx Cloud - Main Job
🔇 Additional comments (4)
docs/node/package.json (1)

16-16: New Workspace Dependency Declaration

The addition of "tevm": "workspace:^" is clear and correctly placed within the dependencies block. This declaration ensures that the workspace version of the Tevm package is used. Please verify that your build system and package manager fully support the workspace: protocol, and that the version resolution aligns with your monorepo setup.

packages/node/src/createTevmNode.js (2)

145-149: LGTM: Clean implementation of viem transport support.

The changes correctly handle both function-style and object-style transports, ensuring consistent access to the request method.


342-346: LGTM: Consistent deep copy implementation for fork transport.

The changes correctly preserve the fork transport during deep copy operations, maintaining consistency with the transport handling pattern.

.changeset/smart-buses-brake.md (1)

1-64: LGTM: Appropriate version bumps and clear description.

The patch version bumps are appropriate for the feature addition, and the description clearly communicates the changes.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🔭 Outside diff range comments (2)
docs/node/docs/pages/advanced/custom-precompiles.test.ts (2)

101-111: 🛠️ Refactor suggestion

Improve error handling in the gas calculation precompile.

Instead of throwing an error, consider returning an EvmError for consistency with other precompiles.

 call: async ({ data, gasLimit }) => {
   // Charge 100 gas per byte
   const gasUsed = BigInt(data.length * 100)
   if (gasUsed > gasLimit) {
-    throw new Error('Out of gas')
+    return {
+      returnValue: new Uint8Array(),
+      exceptionError: new EvmError(EvmErrorMessage.OUT_OF_GAS),
+      executionGasUsed: gasLimit,
+    }
   }
   return {

138-146: 🛠️ Refactor suggestion

Consider using EvmError for error handling.

For consistency with other error handling patterns, consider using EvmError instead of throwing a generic Error.

 call: async ({ data }) => {
   if (data.length === 0) {
-    throw new Error('Empty input not allowed')
+    return {
+      returnValue: new Uint8Array(),
+      exceptionError: new EvmError(EvmErrorMessage.INVALID_INPUT),
+      executionGasUsed: 200n,
+    }
   }
   return {
🧹 Nitpick comments (16)
docs/node/docs/pages/advanced/custom-precompiles.test.ts (2)

17-24: Consider adding input validation.

While the basic precompile implementation is correct, it might be good to add input validation to handle edge cases.

 call: async ({ data}) => {
+  if (!data || data.length === 0) {
+    return {
+      returnValue: new Uint8Array(),
+      executionGasUsed: 200n,
+    }
+  }
   // Simple precompile that doubles each byte
   const input = Array.from(data)
   return {

51-72: Enhance gas limit handling in the state precompile.

The gas limit check is correctly implemented, but consider adding validation for the input data length to ensure it matches the expected format (32 bytes for key and 32 bytes for value).

 call: async ({ data, gasLimit  }) => {
+  if (data.length !== 64) {
+    return {
+      returnValue: new Uint8Array(),
+      exceptionError: new EvmError(EvmErrorMessage.INVALID_INPUT_LENGTH),
+      executionGasUsed: 200n,
+    }
+  }
   const key = data.slice(0, 32) as Hex
   const value = data.slice(32) as Hex
docs/node/docs/pages/advanced/custom-precompiles.mdx (2)

73-87: Consider documenting gas calculation methodology.

While the gas handling is correctly implemented, it would be helpful to document how the gas cost (200n) was determined.

Add a comment explaining the gas calculation:

 call: async ({ data, gasLimit }) => {
+  // Gas cost breakdown:
+  // - Base cost: 100
+  // - Memory expansion: 50
+  // - Data processing: 50
   const executionGasUsed = 200n

224-228: Consider expanding best practices documentation.

The best practices section could benefit from additional guidance on gas calculation strategies and common pitfalls.

Add the following points to the best practices:

  1. Document the rationale behind gas costs
  2. Provide examples of common gas calculation patterns
  3. List typical gas costs for different operations
docs/node/docs/pages/api/state.mdx (5)

22-46: Comprehensive StateManager Interface Documentation

The StateManager interface now includes a broad range of methods covering account handling, contract code/storage, snapshots, and state proofs. This comprehensive list is very useful.

  • Recommendation: Please double-check that these method signatures are fully consistent with the underlying implementation. If possible, consider adding brief inline comments or annotations for each method to improve future readability.

52-57: Creating a State Manager Example

The updated code snippet for creating a State Manager is concise and demonstrates the new import path along with a configurable logging level.

  • Suggestion: It could be beneficial to list or reference the possible loggingLevel options (e.g., 'info', 'debug', etc.) for clarity.

89-97: Contract Management Example Enhancement

The contract management snippet covers both contract code and storage operations adequately, showing updated usage of putContractCode, getContractCode, putContractStorage, and getContractStorage.

  • Consideration: Adding a brief note about error handling for these asynchronous operations might further improve clarity for users.

155-157: Deep Copy Example in Cache Management

The deep copy snippet is a valuable addition that illustrates how to obtain an independent snapshot of the state.

  • Suggestion: Consider adding a brief comment about any potential performance implications when using deep copies, especially in high-frequency scenarios.

186-194: Robust Error Handling Example

The error-handling snippet effectively demonstrates how to catch errors when retrieving an account, including handling a potential AccountNotFoundError.

  • Suggestion: Ensure that AccountNotFoundError is clearly defined or imported in the context where this example is used so that users know where it originates.
docs/node/docs/pages/core/create-tevm-node.test.ts (2)

46-47: Separate assertions for better test failure debugging.

The combined assertion makes it harder to identify which condition failed. Consider separating the assertions for better error messages.

-      expect(node.miningConfig.type === 'interval' && node.miningConfig.interval).toBe(12_000)
+      expect(node.miningConfig.type).toBe('interval')
+      expect(node.miningConfig.interval).toBe(12_000)

62-62: Remove debug console.log statement.

Debug logging should not be included in test files as it pollutes test output.

-          console.log(data, gasLimit)
docs/node/docs/pages/core/forking.test.ts (2)

110-112: Replace non-null assertions with proper null checking.

Using ! assertions could mask potential runtime errors. Consider proper null checking instead.

-      expect(usdcContract!.balance).toBeDefined()
-      expect(usdcContract!.nonce).toBeDefined()
-      expect(usdcContract!.codeHash).toBeDefined()
+      expect(usdcContract?.balance).toBeDefined()
+      expect(usdcContract?.nonce).toBeDefined()
+      expect(usdcContract?.codeHash).toBeDefined()

-      account!.balance += 1000000000000000000n
+      if (!account) {
+        throw new Error('Account not found')
+      }
+      account.balance += 1000000000000000000n

Also applies to: 126-130


146-157: Make performance test more robust.

Timing-based tests can be flaky due to system load and other factors. Consider using a relative threshold or counting actual network requests instead.

-      expect(cachedAccess).toBeLessThan(firstAccess)
+      // Allow for some variance but ensure significant improvement
+      expect(cachedAccess).toBeLessThan(firstAccess * 0.5)
docs/node/docs/pages/core/create-tevm-node.mdx (1)

141-163: Enhanced Precompile Registration for Improved Type Safety
The changes in the "Custom Precompiles" section show a clear update: using both createContract and parseAbi to define the precompile, and then registering it via myPrecompile.precompile(). This enhances readability and type safety. Consider adding a brief note explaining why this approach is preferred over directly assigning an address.

docs/node/docs/pages/advanced/txpool.mdx (1)

174-183: Use of Helper Functions for Transaction Creation
The code snippet for creating transactions now recommends helper functions (parseEther, gweiToWei) for value and fee conversions. This enhances type safety and clarity, though ensure that these helper functions are documented elsewhere in the project.

docs/node/docs/pages/core/managing-state.mdx (1)

47-61: Standardizing Account Creation/Modification
Switching to EthjsAccount.fromAccountData for account creation is a welcome improvement. This approach should be documented as the preferred method over direct instantiation.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 970842e and c2264d5.

⛔ Files ignored due to path filters (4)
  • docs/node/docs/dist/.vocs/search-index-6b680a3c.json is excluded by !**/dist/**
  • docs/node/docs/dist/llms-full.txt is excluded by !**/dist/**
  • docs/node/docs/dist/llms.txt is excluded by !**/dist/**
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (20)
  • docs/node/docs/pages/advanced/custom-precompiles.mdx (8 hunks)
  • docs/node/docs/pages/advanced/custom-precompiles.test.ts (10 hunks)
  • docs/node/docs/pages/advanced/receipts-and-logs.mdx (4 hunks)
  • docs/node/docs/pages/advanced/receipts-and-logs.test.ts (7 hunks)
  • docs/node/docs/pages/advanced/txpool.mdx (1 hunks)
  • docs/node/docs/pages/advanced/txpool.test.ts (2 hunks)
  • docs/node/docs/pages/api/memory-client.test.ts (1 hunks)
  • docs/node/docs/pages/api/methods.test.ts (1 hunks)
  • docs/node/docs/pages/api/state.mdx (4 hunks)
  • docs/node/docs/pages/api/state.test.ts (7 hunks)
  • docs/node/docs/pages/api/tevm-call.mdx (5 hunks)
  • docs/node/docs/pages/api/tevm-call.test.ts (1 hunks)
  • docs/node/docs/pages/core/create-tevm-node.mdx (6 hunks)
  • docs/node/docs/pages/core/create-tevm-node.test.ts (5 hunks)
  • docs/node/docs/pages/core/forking.mdx (5 hunks)
  • docs/node/docs/pages/core/forking.test.ts (3 hunks)
  • docs/node/docs/pages/core/managing-state.mdx (10 hunks)
  • docs/node/docs/pages/core/managing-state.test.ts (10 hunks)
  • docs/node/docs/pages/core/tevm-node-interface.test.ts (4 hunks)
  • docs/node/package.json (1 hunks)
✅ Files skipped from review due to trivial changes (3)
  • docs/node/docs/pages/api/memory-client.test.ts
  • docs/node/docs/pages/api/tevm-call.test.ts
  • docs/node/docs/pages/api/methods.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • docs/node/package.json
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: Nx Cloud Agents (6)
  • GitHub Check: Nx Cloud Agents (5)
  • GitHub Check: Nx Cloud Agents (4)
  • GitHub Check: Nx Cloud Agents (3)
  • GitHub Check: Nx Cloud Agents (2)
  • GitHub Check: Nx Cloud Agents (1)
  • GitHub Check: Nx Cloud - Main Job
🔇 Additional comments (65)
docs/node/docs/pages/advanced/custom-precompiles.test.ts (1)

2-2: LGTM! Import changes look good.

The addition of EvmError and EvmErrorMessage imports aligns with the enhanced error handling approach.

Also applies to: 7-7

docs/node/docs/pages/advanced/custom-precompiles.mdx (2)

20-20: LGTM! Basic example is well documented.

The example correctly demonstrates the basic usage of custom precompiles with proper gas handling.

Also applies to: 28-35


253-256: LGTM! Error handling documentation is comprehensive.

The error handling section properly documents the use of EvmError types and important checks.

docs/node/docs/pages/api/state.mdx (9)

13-14: Alternative Import Path Clarification

The new note ("Or use tevm/state if you have the main tevm package installed") clearly informs users of an alternate import path, which is helpful for maintainers who bundle the main package.


19-20: Interface Introduction Update

The updated introductory text ("The main interface for managing Ethereum state:") sets a clear expectation for what follows. It effectively prefaces the interface declaration.


64-68: Account Management Usage Example

The example for account management now uses the updated API calls (e.g., getAccount, putAccount, deleteAccount, modifyAccountFields) correctly. The usage is clear and straightforward.


99-101: Contract Code Operations Clarity

The updated code segment demonstrates how contract code is set and retrieved, which reinforces the new API behavior.


103-105: Contract Storage Retrieval Example

The snippet correctly shows how to retrieve the contract storage value immediately after setting it. This sequential flow is well demonstrated.


143-144: State Dumping Range Example

The example usage of dumpStorageRange now correctly uses a bigint literal (4n) for the start key and a numeric limit. This clarifies the intended argument types.


163-165: Ensuring Readiness with ready()

The "Always await ready()" example is effective in reiterating the importance of awaiting asynchronous initialization.


169-176: Atomic Operations with Checkpoints

The checkpoint, commit, and revert example is clear and demonstrates how to manage state changes atomically. This practical usage example is helpful for developers dealing with complex state transitions.


180-182: Cache Clearing Best Practice

This snippet emphasizes the importance of managing memory usage by clearing caches periodically. It is clear and to the point.

docs/node/docs/pages/api/tevm-call.mdx (12)

1-4: Front Matter Update
The YAML front matter now clearly demarcates the document metadata with a closing separator on line 4. Please verify that the document renders correctly on the documentation site.


15-16: Updated Imports Including PREFUNDED_ACCOUNTS
The import statement on line 16 now includes PREFUNDED_ACCOUNTS along with createTevmNode. This aligns the examples with the new data source for the from address. Ensure that PREFUNDED_ACCOUNTS is properly defined and exported from the tevm package.


21-23: Updated Call API Example Parameters
The basic usage example now sets the from address to PREFUNDED_ACCOUNTS[0].address and uses a concrete WETH address for to, while the data parameter is set to an empty call. This improves clarity on how to correctly populate these fields.


95-103: Added Example ERC20 ABI for balanceOf
The example now includes a concrete ERC20 ABI declaration for the balanceOf function. This change removes ambiguity by replacing the previous placeholder and provides a clear, reusable example.


105-110: Enhanced Function Call with encodeFunctionData
In the example call (lines 105-110), the snippet now explicitly sets the to and from parameters and leverages encodeFunctionData with the updated ABI, function name, and arguments. This change not only improves consistency but also shows a more realistic usage scenario.


114-116: Clear Result Decoding Example
The snippet using decodeFunctionResult (lines 114-116) now clearly passes the ABI and function name. This explicitness helps users to understand how to correctly decode the call result.


124-126: Updated Contract Deployment Bytecode
The contract deployment example now provides a specific bytecode string that implements a simple contract (returning 42). Please verify that the provided bytecode is valid and behaves as expected in a deployment scenario.


128-129: Consistent Deployment Parameters
In the deployment example, the from address is now set to PREFUNDED_ACCOUNTS[0].address and the data field is assigned the explicit bytecode. This ensures consistency with the other examples. Check that the createTransaction: true flag functions as intended.


140-148: Enhanced State Override Example
The state override example (lines 140-148) now uses PREFUNDED_ACCOUNTS[0].address for the from parameter and updates the state override mapping with clear values (balance, nonce, code, and state). This makes it easier to simulate specific account states during testing.


158-160: Updated Debug Trace Call Parameters
The debug trace example now consistently uses PREFUNDED_ACCOUNTS[0].address for the from address and the specified WETH address for to. These changes help standardize the examples across the documentation.


165-169: Conditional Trace Logging Enhancement
The modification on lines 165-169 adds a check for result.trace before iterating over structLogs, preventing potential runtime errors if the trace is undefined. This condition improves robustness when handling debug traces.


174-174: Streamlined Higher-Level API Commentary
The trailing line beginning with "While callHandler" on line 174 has been updated (or truncated) to streamline the documentation. Please confirm that this removal does not omit any essential information needed for understanding higher-level APIs.

docs/node/docs/pages/core/create-tevm-node.test.ts (3)

54-60: LGTM! Enhanced type safety in precompile definition.

The use of createContract with parseAbi improves type safety and provides better contract interface definition.


71-71: LGTM! Improved precompile registration pattern.

The use of myPrecompile.precompile() provides a clearer API for registering precompiles.


18-18:

❓ Verification inconclusive

Standardize transport initialization pattern.

The transport initialization has been updated to use a consistent pattern with an empty object parameter: http(url)({}). This change aligns with viem's transport configuration style.

Let's verify this is the recommended pattern in viem's documentation:

Also applies to: 105-105


🌐 Web query:

What is the correct way to initialize HTTP transport in viem?

💡 Result:

To initialize an HTTP transport in Viem correctly:

  1. Basic Initialization
    Import http from viem and use it as your transport provider when creating a client:
import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'

const client = createPublicClient({
  chain: mainnet,
  transport: http('https://eth-mainnet.g.alchemy.com/v2/YOUR_API_KEY')
})
  1. Key Configuration Options
    The HTTP transport supports several optional parameters:
const transport = http('https://rpc-url', {
  batch: true,       // Enable Batch JSON-RPC (default false)
  retryCount: 5,     // Max retry attempts (default 3)
  retryDelay: 100    // Base retry delay in ms (default 150)
})
  1. Authentication Best Practice
    Always provide an authenticated RPC endpoint to avoid rate limiting[2][5]. Public nodes should only be used for testing:
// Recommended authenticated setup
transport: http('https://eth-mainnet.g.alchemy.com/v2/your-api-key')

// Avoid public nodes in production
transport: http() // Falls back to chain's public RPC
  1. Batch Request Optimization
    Enable batch processing for multiple concurrent requests:
const transport = http('https://rpc-url', { batch: true })

// Executes as single batch request
const [balance, block] = await Promise.all([
  client.getBalance(...),
  client.getBlock(...)
])
  1. Full Client Configuration
    Combine with other client options for complete setup:
import { createWalletClient } from 'viem'

const walletClient = createWalletClient({
  chain: mainnet,
  transport: http(),
  account: privateKeyToAccount('0x...')
})
```[1][4][7]

The core initialization requires specifying your JSON-RPC endpoint in the `http()` transport configuration while creating either a public or wallet client[1][5][7]. Batch processing and retry configurations are recommended for production-grade applications[2][9].

Citations:

- 1: https://viem.sh/docs/clients/transports/http.html
- 2: https://viem-iyn6kgwt-wxqdoit.4everland.app/docs/clients/transports/http
- 3: https://docs.devicewise.com/Content/Products/GatewayDevelopersGuide/EnterpriseConnectivity/Defining-an-HTTP-transport.htm
- 4: https://viem.sh/docs/clients/custom
- 5: https://docs.soneium.org/docs/builders/tutorials/client-integration/viem
- 6: https://docs.moonbeam.network/builders/ethereum/libraries/viem/
- 7: https://viem.sh/docs/clients/public.html
- 8: https://viem.sh/docs/clients/transports/custom.html
- 9: https://viem.sh/docs/clients/transports/websocket
- 10: https://code.zksync.io/tutorials/guide-viem

---



</details>

**Standardize transport initialization pattern.**

The transport configuration was updated to use a consistent pattern with an explicit empty options object, as seen with  
```typescript
transport: http('https://mainnet.infura.io/v3/YOUR-KEY')({})

While this pattern standardizes the initialization across the codebase (lines 18 and 105), the latest viem documentation shows that the recommended basic initialization is to invoke http(...) directly (or pass configuration as a second argument, e.g., http('https://rpc-url', { batch: true })). If no additional configuration is needed, consider using the canonical form:

transport: http('https://mainnet.infura.io/v3/YOUR-KEY')

Please verify whether the extra invocation with an empty object is intentional for future configurability or if it should be aligned with the documented patterns.

  • Affected locations:
    • docs/node/docs/pages/core/create-tevm-node.test.ts: Line 18
    • docs/node/docs/pages/core/create-tevm-node.test.ts: Line 105
docs/node/docs/pages/api/state.test.ts (3)

9-11: LGTM! Simplified state manager initialization.

The removal of the common parameter simplifies the API while maintaining functionality.

Also applies to: 24-24


25-25: LGTM! Enhanced type safety in address and data handling.

The use of createAddress and hexToBytes utility functions improves type safety and standardizes data handling across the codebase.

Also applies to: 48-50


109-109: LGTM! Consistent use of BigInt for block numbers.

The use of BigInt for the storage range aligns with the standard practice of using BigInt for block numbers.

docs/node/docs/pages/core/tevm-node-interface.test.ts (3)

26-26: LGTM! Standardized transaction creation pattern.

The use of createImpersonatedTx provides a consistent and type-safe way to create transactions for testing.

Also applies to: 60-65


71-85: LGTM! Comprehensive receipt validation.

The enhanced receipt validation properly checks for post-Byzantium fields and provides thorough type checking.


92-106: LGTM! Thorough log structure validation.

The enhanced log validation ensures proper structure and includes comprehensive checks for all log components.

docs/node/docs/pages/core/managing-state.test.ts (4)

2-4: LGTM!

The imports are correctly added and align with the changes in the codebase.


23-23: LGTM! Improved type safety and standardized address handling.

The changes enhance type safety by using createAddress for address creation and EthjsAccount.fromAccountData for account data initialization.

Also applies to: 38-38


69-70: LGTM! Enhanced storage handling with proper type conversion.

The changes improve type safety by using hexToBytes to convert hex strings to byte arrays for storage operations.

Also applies to: 78-79


97-111: LGTM! Consistent implementation of state checkpoint operations.

The changes maintain consistency with the codebase's patterns for address handling and storage operations.

docs/node/docs/pages/advanced/txpool.test.ts (4)

11-24: LGTM! Enhanced transaction handling and pool operations.

The changes improve transaction handling by using createImpersonatedTx for transaction creation and standardize pool operations with txPool methods.

Also applies to: 31-56


63-81: LGTM! Consistent implementation of advanced transaction features.

The changes maintain consistency in handling transaction replacement and expiry scenarios.

Also applies to: 93-112


119-131: LGTM! Improved error handling and validation.

The changes enhance error handling for invalid transactions and nonce gaps.

Also applies to: 141-165


173-211: LGTM! Maintained performance characteristics.

The changes preserve the performance characteristics for handling concurrent transactions.

docs/node/docs/pages/advanced/receipts-and-logs.test.ts (4)

8-12: LGTM! Enhanced code readability with constants.

The addition of CONTRACT_BYTECODE and EMIT_EVENT_SELECTOR constants improves code readability and maintainability.


89-132: LGTM! Comprehensive receipt handling test coverage.

The changes provide thorough test coverage for receipt handling with multiple scenarios.


237-269: LGTM! Comprehensive log filtering test coverage.

The changes provide thorough test coverage for log filtering with multiple scenarios.


276-293: LGTM! Improved error handling test coverage.

The changes enhance error handling for non-existent receipts and invalid filters.

docs/node/docs/pages/advanced/receipts-and-logs.mdx (4)

15-44: LGTM! Clear and comprehensive receipt management examples.

The examples effectively demonstrate receipt management with proper error handling and type safety.


71-132: LGTM! Clear and comprehensive event logs examples.

The examples effectively demonstrate contract deployment, event emission, and log querying with multiple filter scenarios.


134-152: LGTM! Clear error handling examples.

The examples effectively demonstrate handling of non-existent receipts and invalid filters.


177-190: LGTM! Clear best practices examples.

The examples effectively demonstrate type safety and proper error handling patterns.

docs/node/docs/pages/core/forking.mdx (4)

25-27: Ensure Consistent Invocation of the Transport Function
The example now correctly invokes the http function with an empty object (({})), which aligns with the new requirements. Verify that this pattern is consistently followed elsewhere in the docs.


33-35: Clarify the Transport Function Requirement in the Callout
The updated callout now clearly states that the transport function must be called with an empty object. This clarifies usage for users familiar with EIP-1193 providers and viem style transports.


46-56: Verify Reforking Strategy Example
The reforking example correctly demonstrates using the source node as a transport with proper conversion of the current block using hexToBigInt. Make sure that users understand that the same pattern should be applied when forking from a live network or another Tevm instance.


83-101: Usage of Deep Copy with Address Handling
The deep copy example now makes use of createAddress for improved type safety. This is a good enhancement for clarity and consistency in address management.

docs/node/docs/pages/core/create-tevm-node.mdx (2)

85-96: Updated Mining Configuration Examples
The mining configuration examples now cover both auto and interval-based mining. These examples clearly illustrate the new structured type for miningConfig (e.g. { type: 'interval', interval: <number> }). This change improves clarity for users setting up different node behaviors.


193-197: Reinforce Best Practice by Awaiting Node Readiness
Including await node.ready() in the best practices section serves as an important reminder to ensure that node initialization completes before proceeding.

docs/node/docs/pages/advanced/txpool.mdx (5)

2-4: Updated Document Title and Description
The new title "Transaction Pool" and the revised description properly reflect the enhanced documentation and functionality updates for managing pending Ethereum transactions.


12-33: Quick Start Example Using New Transaction Methods
The quick start example now demonstrates the use of createImpersonatedTx alongside obtaining the TxPool via await node.getTxPool(). This clearly illustrates the intended workflow for quickly setting up and interacting with the transaction pool.


89-104: Demonstrate Effective Transaction Replacement
The transaction replacement example illustrates replacing an original transaction by submitting a new one with a higher gas fee. The inline comment regarding the requirement for at least a 10% gas price bump is clear and informative.


218-228: Memory Management and Cleanup Guidance
The inclusion of a cleanup cycle example and pool size monitoring is a valuable addition. This example provides practical guidance on maintaining optimal performance of the transaction pool.


235-248: Comprehensive API Reference for TxPool
The newly updated API reference section for the TxPool class now includes all major functions and method signatures. This should help developers quickly understand available actions.

docs/node/docs/pages/core/managing-state.mdx (5)

17-22: Simplified Node and State Manager Initialization
The updated snippet for initializing the node and accessing the state manager is succinct and clear. It demonstrates best practices in setting up the VM for state operations.


29-32: Improved Address Handling in Account Reading
The replacement of hardcoded addresses with createAddress ensures better type safety. This change modernizes the example and is consistent with updates in other documentation parts.


115-122: Consistent Use of Address and Storage Formatting Utilities
The examples for reading and writing storage now use createAddress and hexToBytes from tevm/utils, which enhances consistency and clarifies expected data formats.


155-184: Robust Example for State Checkpoints and Atomic Updates
The checkpoint example demonstrates proper use of commit and revert within a try–catch block. This is an excellent illustration of handling atomic state updates. Consider noting any version-specific requirements if applicable.


242-254: Effective Error-Handling Best Practices
The best practices snippet for error handling in state operations gives clear instructions (e.g., throwing 'Account not found'). This ensures that developers are aware of potential pitfalls and how to handle them gracefully.

Comment on lines +74 to 93
it('should modify state in forked node', async () => {
// @ts-ignore TODO: Fix viem version mismatch
const node = createTevmNode({
fork: {
// @ts-ignore TODO: Fix viem version mismatch
transport: http('https://mainnet.infura.io/v3/YOUR-KEY'),
},
})

// Get USDC contract state
const USDC_ADDRESS = '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48'
const vm = await node.getVm()
const usdcContract = await vm.stateManager.getAccount(USDC_ADDRESS)
const address = createAddress('0x1234567890123456789012345678901234567890')
const account = await vm.stateManager.getAccount(address)
if (account) {
account.balance += 1000000000000000000n // Add 1 ETH
await vm.stateManager.putAccount(address, account)
}

expect(usdcContract).toBeDefined()
expect(usdcContract.balance).toBeDefined()
expect(usdcContract.nonce).toBeDefined()
expect(usdcContract.codeHash).toBeDefined()
const updatedAccount = await vm.stateManager.getAccount(address)
expect(updatedAccount?.balance).toBe(account?.balance)
})
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Remove duplicate test case.

The test case "should modify state in forked node" appears twice with nearly identical implementation. Consider removing one instance to improve maintainability.

Also applies to: 115-131

import { performance } from 'node:perf_hooks'

describe('Forking', () => {
describe('Basic Forking', () => {
it('should create a forked node', async () => {
it('should create forked node', async () => {
// @ts-ignore TODO: Fix viem version mismatch
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

⚠️ Potential issue

🧩 Analysis chain

Address viem version mismatch.

Multiple TODO comments indicate a version mismatch with viem that needs to be resolved to prevent potential runtime issues.

Let's check the current version constraints:

Also applies to: 26-26, 43-43, 58-58, 78-78, 118-118


🏁 Script executed:

#!/bin/bash
# Check package.json for viem version constraints
cat package.json | jq '.dependencies.viem, .devDependencies.viem'

Length of output: 77


Resolve Viem Version Mismatch

The test file docs/node/docs/pages/core/forking.test.ts (and similar TODOs at lines 10, 26, 43, 58, 78, 118) still includes comments flagging a viem version mismatch. Our check confirms that viem is not explicitly defined in package.json (both dependencies and devDependencies return null), which means we're likely relying on a transitive version that may not be consistent. To prevent potential runtime issues, please either add an explicit version for viem in package.json or adjust the test/code to properly handle the version discrepancy.

@roninjin10 roninjin10 force-pushed the 02-23-_sparkles_feat_offer_more_forking_options_and_test_docs branch from d766cf3 to 22d5afe Compare February 24, 2025 04:04
@roninjin10 roninjin10 merged commit 23251fb into main Feb 24, 2025
9 of 11 checks passed
@roninjin10 roninjin10 deleted the 02-23-_sparkles_feat_offer_more_forking_options_and_test_docs branch February 24, 2025 04:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant